import requests
import base64
import json
import execjs
from web.Script.ScriptTools import Config


class ScriptHaiJiao:
    def __init__(self):
        self._domain = 'https://www.hj3be22.top'
        self.headers = {
            "X-User-Id": "171682636601",
            "X-User-Token": "9e049fd5ed244a3490f903ae12ce4a04"
        }
        self.Config = Config.ScriptConfig()

        self.js_decode = r"""
        function a(b) {
         let o = (new w).decode(b);
         return o;
        }
         function w() {
        var e = "ABCD*EFGHIJKLMNOPQRSTUVWX#YZabcdefghijklmnopqrstuvwxyz1234567890"
            , t = (this.encode = function (i) {
                var a, n, o, r, s, c, l = "", d = 0;
                for (i = t(i); d < i.length;)
                    o = (a = i.charCodeAt(d++)) >> 2,
                        r = (3 & a) << 4 | (a = i.charCodeAt(d++)) >> 4,
                        s = (15 & a) << 2 | (n = i.charCodeAt(d++)) >> 6,
                        c = 63 & n,
                        isNaN(a) ? s = c = 64 : isNaN(n) && (c = 64),
                        l = l + e.charAt(o) + e.charAt(r) + e.charAt(s) + e.charAt(c);
                return l
            }
                ,
                this.decode = function (t) {
                    var a, n, o, r, s, c, l = "", d = 0;
                    for (t = t.replace(/[^A-Za-z0-9\*\#]/g, ""); d < t.length;)
                        o = e.indexOf(t.charAt(d++)),
                            a = (15 & (r = e.indexOf(t.charAt(d++)))) << 4 | (s = e.indexOf(t.charAt(d++))) >> 2,
                            n = (3 & s) << 6 | (c = e.indexOf(t.charAt(d++))),
                            l += String.fromCharCode(o << 2 | r >> 4),
                            64 != s && (l += String.fromCharCode(a)),
                            64 != c && (l += String.fromCharCode(n));
                    return i(l)
                }
                ,
                function (e) {
                    e = e.replace(/\r\n/g, "\n");
                    for (var t = "", i = 0; i < e.length; i++) {
                        var a = e.charCodeAt(i);
                        a < 128 ? t += String.fromCharCode(a) : t = 127 < a && a < 2048 ? (t += String.fromCharCode(a >> 6 | 192)) + String.fromCharCode(63 & a | 128) : (t = (t += String.fromCharCode(a >> 12 | 224)) + String.fromCharCode(a >> 6 & 63 | 128)) + String.fromCharCode(63 & a | 128)
                    }
                    return t
                }
            )
            , i = function (e) {
                for (var t, i, a = "", n = 0, o = 0; n < e.length;)
                    (t = e.charCodeAt(n)) < 128 ? (a += String.fromCharCode(t),
                        n++) : 191 < t && t < 224 ? (o = e.charCodeAt(n + 1),
                            a += String.fromCharCode((31 & t) << 6 | 63 & o),
                            n += 2) : (o = e.charCodeAt(n + 1),
                                i = e.charCodeAt(n + 2),
                                a += String.fromCharCode((15 & t) << 12 | (63 & o) << 6 | 63 & i),
                                n += 3);
                return a
            }
    }
    """

        # 管理者
        self.admin_wx = 'duyanbz'
        self.admin_email = '18171759943@163.com'



    # 解密
    def decrypt(self, data):
        for i in range(3):
            data = base64.b64decode(data)
        data = data.decode('utf-8')
        return json.loads(data)

    # 热帖子列表
    def get_hot_list(self, page = 1):
        """
        page: 最多只能为50
        """
        page = int(page)
        if page < 1:
            page = 1
        elif page > 50:
            page = 50
        url = self._domain + '/api/topic/hot/topics'
        self.headers['User-Agent'] = self.Config.get_ua()
        params_data = {
            "page": page
        }
        response = requests.get(url, params = params_data, headers = self.headers).json()
        if response['success']:
            response['data'] = self.decrypt(response['data'])
            return response
        else:
            return response

    # 根据帖子pid获取帖子内容
    def get_topic_content(self, pid):
        url = self._domain + f'/api/topic/{pid}'
        self.headers['User-Agent'] = self.Config.get_ua()

        response = requests.get(url, headers = self.headers).json()
        if response['success']:
            response['data'] = self.decrypt(response['data'])
            if response['data']['attachments'] is None:
                return response
            else:
                for obj in response['data']['attachments']:
                    if obj['category'] == 'video':
                        if obj['remoteUrl'] == '':
                            video_data = {
                                "id": obj['id'],
                                "line": '',
                                "resource_id": pid,
                                "resource_type": 'topic'
                            }
                            video_response = requests.post(url = self._domain + '/api/attachment',
                                                           headers = self.headers,
                                                           json = video_data).json()
                            if video_response['success']:
                                video_response['data'] = self.decrypt(video_response['data'])
                                obj['remoteUrl'] = self._domain + video_response['data']['remoteUrl']
                            else:
                                json_data = {
                                    'id': obj['id'],
                                    'resource_type': 'topic',
                                    'resource_id': response['data']['topicId'],
                                    'line': '',
                                }
                                video_response = requests.post(url = self._domain + '/api/attachment',
                                                               headers = self.headers, json = json_data).json()
                                video_response['data'] = self.decrypt(video_response['data'])
                                if video_response['success']:
                                    obj['remoteUrl'] = self._domain + video_response['data']['remoteUrl']
                                else:
                                    obj[
                                        'remoteUrl'] = f'失败了, 请联系管理人员维修: 国内微信: {self.admin_wx} 邮箱: {self.admin_email}, 问题描述: 视频请求失败, ID为: {obj['id']}, 帖子id: {pid}'
                        else:
                            obj['remoteUrl'] = self._domain + obj['remoteUrl']
                return response
        else:
            return response

    # 搜索帖子
    def search_topic(self, keyword, page = 1):
        page = int(page)
        if page < 1:
            page = 1
        elif page > 50:
            page = 50
        url = self._domain + '/api/topic/search'
        self.headers['User-Agent'] = self.Config.get_ua()

        params_data = {
            "key": keyword,
            "page": page,
            "node_id": 0
        }
        response = requests.post(url, headers = self.headers, data = params_data).json()
        if response['success']:
            response['data'] = self.decrypt(response['data'])
            return response
        else:
            return response


if __name__ == '__main__':
    script = ScriptHaiJiao()
    print(script.search_topic("聊天", page = 2))
